package com.zust513.controller;

import com.zust513.entity.*;

import com.zust513.service.OrderService;
import com.zust513.service.rrr.CourierServiceR;
import com.zust513.utils.ServletContextUtil;
import jakarta.servlet.http.HttpServletRequest;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;

import java.math.BigDecimal;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Controller
@RequestMapping("/courier")
public class CourierController {

    @Autowired
    private CourierServiceR courierService;

    @Autowired
    private OrderService orderService;


    // 配送员主页面
    @GetMapping("/main")
    public String courierMainPage(Model model) {
        // 获取当前用户的 ID
        Integer userId = ServletContextUtil.getCurUser().getUserId();
        // 调用服务方法进行联合查询
        Map<String, Object> userCourierInfo = courierService.findUserAndCourierByUserId(userId);
        // 将查询结果添加到 Model 中
        model.addAttribute("userCourierInfo", userCourierInfo);

        List<Integer> regionIds = courierService.getRegionIdsByCourierId(userId);
        model.addAttribute("regionIds", regionIds);
        return "courier_main";
    }

    // 需配送订单
    @GetMapping("/pending-orders")
    public String getPendingOrders(Model model) {
        Integer courierId = ServletContextUtil.getCurUser().getUserId();
        List<Order> pendingOrders = orderService.getPendingOrdersByCourierId(courierId);
        model.addAttribute("pendingOrders", pendingOrders);
        return "courier_pending_orders";
    }

    // 总配送订单
    @GetMapping("/total-orders")
    public String getTotalOrders(Model model) {
        // 调用OrderService的方法获取所有订单
        List<Order> allPendingOrders = orderService.getAllPendingOrders();
        // 将订单数据添加到模型中
        model.addAttribute("allPendingOrders", allPendingOrders);
        return "courier_total_orders";
    }

    // 订单管理页面
    @GetMapping("/order_management")
    public String showOrderManagement(Model model) {
        User user = ServletContextUtil.getCurUser();
        Integer courierId = user.getUserId();
        List<Order> orders = orderService.getAllOrdersByCourierId(courierId);
        model.addAttribute("orders", orders);
        return "order_management";
    }

    // 收益管理页面
    @GetMapping("/earnings_management")
    public String showEarningsManagement(Model model) {
        User user = ServletContextUtil.getCurUser();
        Integer courierId = user.getUserId();

        // 获取当前余额
        BigDecimal balance = courierService.getBalanceByCourierId(courierId);
        model.addAttribute("balance", balance != null ? balance : BigDecimal.ZERO);

        return "earnings_management";
    }

    // 提现接口
    @PostMapping("/withdraw")
    public String handleWithdraw(@RequestParam Integer amount, Model model) {
        User user = ServletContextUtil.getCurUser();
        Integer courierId = user.getUserId();

        try {
            // 调用服务层执行提现
            courierService.withdraw(courierId, amount);
            model.addAttribute("success", "提现成功！金额已转入银行卡");
        } catch (IllegalArgumentException e) {
            model.addAttribute("error", e.getMessage());
        }

        // 刷新余额显示
        BigDecimal balance = courierService.getBalanceByCourierId(courierId);
        model.addAttribute("balance", balance != null ? balance : BigDecimal.ZERO);

        return "earnings_management";
    }

    // 接取订单
    @PostMapping("/accept-order")
    public String handleAcceptOrder(@RequestParam Integer orderId, @RequestParam Integer courierId) {
        try {
            orderService.acceptOrder(orderId, courierId);
            return "redirect:/courier/total-orders";
        } catch (RuntimeException e) {
            if (e.getMessage().contains("配送员当前订单数量已达到上限")) {
                return "redirect:/courier/pending-orders?error=order_limit_exceeded";
            } else {
                // 其他异常处理
                return "redirect:/courier/pending-orders?error=unknown";
            }
        }
    }

    // F0030203 接单并进行配送
    @PostMapping("/{courierId}/accept-order")
    @ResponseBody
    public Map<String, Object> acceptOrder(@PathVariable Integer courierId,
                                           @RequestParam Integer orderId) {
        Map<String, Object> result = new HashMap<>();
        try {
            orderService.acceptOrder(orderId, courierId);
            result.put("success", true);
        } catch (Exception e) {
            result.put("success", false);
            result.put("message", e.getMessage());
        }
        return result;
    }

    // 确认送达
    @PostMapping("/confirm-delivery/{orderId}")
    public String confirmDelivery(@PathVariable("orderId") Integer orderId) {
        orderService.confirmDelivery(orderId);
        return "redirect:/courier/pending-orders";
    }

    // F0030102 该配送人员运营范围
    @GetMapping("/regions/{courierId}")
    public String getCourierRegions(@PathVariable Integer courierId, Model model) {
        List<CourierRegion> regions = courierService.getCourierRegions(courierId);
        model.addAttribute("regions", regions);
        return "courier_operation_areas"; // 对应 courier_operation_areas.html
    }

    @GetMapping("/regions")
    public String getCourierRegions(Model model) {
        User user = ServletContextUtil.getCurUser();
        Integer courierId = user.getUserId();
        List<CourierRegion> regions = courierService.getCourierRegions(courierId);
        model.addAttribute("regions", regions);
        return "courier_operation_areas";
    }

    // F0030201 该楼配送订单总量统计
    @GetMapping("/order-stats/{courierId}")
    public String getOrderStats(@PathVariable Integer courierId, Model model) {
        int todayOrders = orderService.getTodayOrdersByCourierId(courierId);
        int weekOrders = orderService.getWeekOrdersByCourierId(courierId);
        int monthOrders = orderService.getMonthOrdersByCourierId(courierId);
        int allOrders = orderService.getTotalDeliveryOrdersByCourierId(courierId);

        model.addAttribute("todayOrders", todayOrders);
        model.addAttribute("weekOrders", weekOrders);
        model.addAttribute("monthOrders", monthOrders);
        model.addAttribute("allOrders", allOrders);

        return "courier_total_orders"; // 对应 courier_total_orders.html
    }

    // F0030202 向空闲楼配送员求援
    @PostMapping("/assistance-request")
    @ResponseBody
    public Map<String, Object> sendAssistanceRequest(@PathVariable Integer courierId,
                                                     @RequestParam Integer orderId) {
        Map<String, Object> result = new HashMap<>();
        try {
            courierService.sendAssistanceRequest(courierId, orderId);
            result.put("success", true);
        } catch (Exception e) {
            result.put("success", false);
            result.put("message", e.getMessage());
        }
        return result;
    }

    //配送员接单数量超出
    @PostMapping("/accept-order/{orderId}")
    public String acceptOrder(@PathVariable Integer orderId, HttpServletRequest request, Model model) {
        try {
            Integer courierId = ServletContextUtil.getCurUser().getUserId();
            orderService.acceptOrder(orderId, courierId);
        } catch (RuntimeException e) {
            if ("order_limit_exceeded".equals(e.getMessage())) {
                model.addAttribute("error", "配送员当前订单数量已达到上限，无法接单");
            } else {
                model.addAttribute("error", "发生未知错误：" + e.getMessage());
            }
        }
        return "redirect:/courier/total-orders";
    }

    // F0030204 修改订单状态（未接单，已取餐，送达）
    @PostMapping("/{courierId}/update-order-status/{orderId}/{status}")
    @ResponseBody
    public Map<String, Object> updateOrderStatus(@PathVariable Integer courierId,
                                                 @PathVariable Integer orderId,
                                                 @PathVariable String status) {
        Map<String, Object> result = new HashMap<>();
        try {
            orderService.updateOrderStatus(orderId, status);
            result.put("success", true);
        } catch (Exception e) {
            result.put("success", false);
            result.put("message", e.getMessage());
        }
        return result;
    }

    // F0030301 将收益转入个人账户
    @PostMapping("/transfer-earnings/{orderId}")
    @ResponseBody
    public Map<String, Object> transferEarningsToAccount(@PathVariable Integer courierId,
                                                         @PathVariable Integer orderId) {
        Map<String, Object> result = new HashMap<>();
        try {
            orderService.transferEarningsToCourier(orderId);
            result.put("success", true);
        } catch (Exception e) {
            result.put("success", false);
            result.put("message", e.getMessage());
        }
        return result;
    }

    // F0030302 查看获得配送金的历史订单详情
    @GetMapping("/delivery-records")
    public String getDeliveryRecords(@PathVariable Integer courierId, Model model) {
        List<Order> records = orderService.getDeliveryRecordsByCourierId(courierId);
        model.addAttribute("records", records);
        return "earnings_management"; // 对应 earnings_management.html
    }

    // F0030401 配送员身份注册/注销请求
    @GetMapping("/identity_management")
    public String showIdentityManagement(Model model) {
        User user = ServletContextUtil.getCurUser();
        Integer courierId = user.getUserId();
        Courier courier = courierService.getCourierById(courierId);
        if (courier == null) {
            courier = new Courier();
            courier.setCourierId(courierId);
        }
        model.addAttribute("courier", courier);
        return "identity_management";
    }

/*
    @PostMapping("/register")
    @ResponseBody
    public Map<String, Object> registerCourier(@PathVariable Integer courierId,
                                               @RequestBody Courier courier) {
        Map<String, Object> result = new HashMap<>();
        try {
            courier.setCourierId(courierId);
            courierService.registerCourier(courier);
            result.put("success", true);
        } catch (Exception e) {
            result.put("success", false);
            result.put("message", e.getMessage());
        }
        return result;
    }
*/

    @PostMapping("/cancel-registration")
    @ResponseBody
    public Map<String, Object> cancelRegistration(@PathVariable Integer courierId) {
        Map<String, Object> result = new HashMap<>();
        try {
            courierService.cancelRegistration(courierId);
            result.put("success", true);
        } catch (Exception e) {
            result.put("success", false);
            result.put("message", e.getMessage());
        }
        return result;
    }
}
